<?php
namespace Jykj\Quicklogin\Controller;

/***************************************************************
 *
 *  Copyright notice
 *
 *  (c) 2015 WHB <wanghongbin@ngoos.org>
 *
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/

require_once(\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('quicklogin') . 'Classes/Lib/WxOpenApi.php');
/**
 * The Controller for  Wechat
 */
class WechatController extends CommonController{
	
   
   /**
	 * 生成登录图标
	 * & 生成外部调用代码
	 */
	public function indexAction(){
        
        if($GLOBALS["TSFE"]->fe_user->user) return '';
        
        $state = md5(uniqid(rand(), TRUE));
		$scope = 'get_user_info';
        
        $baseUrl = \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('TYPO3_SITE_URL');
        if($this->settings['wechat']['appId'] != '' && $this->settings['wechat']['appKey'] != ''){
            $formwx = $baseUrl . $this->uriBuilder->setTargetPageUid($this->settings['wechat']['successPid'])->build();
            $wxAPI = new \WxOpenApi(
                    $this->settings['wechat']['appId'], 
                    $this->settings['wechat']['appKey'], 
                    $baseUrl . $this
                        ->uriBuilder
                        ->reset()
                        ->setCreateAbsoluteUri(false)
                        ->setUseCacheHash(FALSE)
                        ->setTargetPageUid($this->settings['wechat']['callbackPid'])
                        ->uriFor('callback',array('from'=>urlencode($formwx)),'Wechat', NULL));

            $wechatUri = $wxAPI->getRequestCodeURL();
            $this->view->assign('wechatUri', $wechatUri);
        }
       
        if($this->settings['qq']['appId'] != ''){
            $formqq = $baseUrl . $this->uriBuilder->setTargetPageUid($this->settings['qq']['successPid'])->build();
            $qqUri = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=".$this->settings['qq']['appId']."&redirect_uri=".urlencode($baseUrl.$this->uriBuilder
					->reset()
                    ->setCreateAbsoluteUri(false)
					->setUseCacheHash(FALSE)
					->setTargetPageUid($this->settings['qq']['callbackPid'])
					->uriFor('callback',array('from'=>urlencode($formqq)),'QQ', NULL))."&state=".$state."&scope=".$scope;
            $this->view->assign('qqUri', $qqUri);
        }
        
        
        if($this->settings['weibo']['appId'] != ''){
            $redirect_uri = $baseUrl . $this->uriBuilder->setTargetPageUid($this->settings['weibo']['callbackPid'])->build();
            $WeiBo = new \SaeTOAuthV2($this->settings['weibo']['appId'],$this->settings['weibo']['appKey']);
            $weiboUrl = $WeiBo->getAuthorizeURL($redirect_uri);
            $this->view->assign('weiboUrl', $weiboUrl);
        }
	}
    
	
	/**
	 * 远程登录成功后回调
	 */
	public function callbackAction(){
        
        $code = $_GET['code'];
        $wxAPI = new \WxOpenApi($this->settings['wechat']['appId'], $this->settings['wechat']['appKey']);
        $str = $wxAPI->getAccessToken($code);
        $response = json_decode($str);
        
        if(isset($response->error)){
			return new \TYPO3\CMS\Extbase\Error\Error('登录错误 ,请重新登录', 1340193849); 
        }else{
			if($userInfo = $this->frontendUserRepository->findByOpenid($response->openid,'openidWechat')){ //判断是否已绑定，未绑定进行绑定
				$userInfo->setAccessTokenWechat($response->access_token);
				$this->frontendUserRepository->update($userInfo);
				$this->redirect('login',NULL,NULL,array('fuser'=>$userInfo,'from'=>$this->request->getArgument('from')));
			}else{
				$this->redirect('bind',NULL,NULL,array('access_token' => $response->access_token, 'openid' => $response->openid, 'from'=>$this->request->getArgument('from')));
			}
			
		}
	}
}